package com.ly.mp.busicen.rule.flow.filter;

import static com.ly.mp.busicen.rule.XruleStrUtils.splitJKH;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ly.mp.busicen.rule.XruleStrUtils;
import com.ly.mp.busicen.rule.flow.IDataVolume;
import com.ly.mp.busicen.rule.flow.IFlowContext;
import com.ly.mp.busicen.rule.flow.IFlowVolume;
import com.ly.mp.busicen.rule.flow.action.IAction;
import com.ly.mp.busicen.rule.flow.action.IActionExecute;
import com.ly.mp.busicen.rule.flow.action.IActionResult;

public class FlowFilterExecuteImpl implements FlowFilterExecute {
	
	Logger log = LoggerFactory.getLogger(FlowFilterExecuteImpl.class);

	@Autowired
	FlowFilterContainer flowFilterContainer;
	
//	@Autowired
//	IFlowInstrumentation instrumentation;

	@Override
	public IActionResult invoke(IActionExecute actionExecute, IAction action, IFlowContext context) {
		String filtersStr = action.filter();

		Queue<String> filterQue = new LinkedBlockingQueue<String>();
		List<String> filters = XruleStrUtils.splitToList(filtersStr, ";");
		filterQue.addAll(filters);
		//添加默认过滤器 用于调用action
		filterQue.add("<execution>");
		FlowInvocation flowInvocation = new FlowInvocation() {

			String statement = "";

			@Override
			public FlowFilter invoker() {
				statement = filterQue.remove();
				FlowFilter flowFilter = flowFilterContainer.filter(splitJKH(statement));			
				//instrumentation.beginFilter(flowFilter, this);
				return flowFilter;
			}

			@Override
			public String statement() {
				return statement;
			}

			@Override
			public IActionExecute execution() {
				return actionExecute;
			}

			@Override
			public IDataVolume dataVolume() {
				return context.dataVolume();
			}
			
			@Override
			public IFlowVolume flowVolume() {
				return context.flowVolume();
			};

			@Override
			public IAction action() {
				return action;
			}
		};
		try {
			FlowResult result = flowInvocation.invoker().invoke(flowInvocation);
			return result.actionResult();
		} catch (Exception e) {
			log.error("{}节点过滤器执行异常",action.action(),e);
			throw e;
		}
		
	}
}
